package com.vframework.base.controller;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.util.StringUtil;
import com.vframework.base.exception.BaseException;
import com.vframework.base.model.BaseMap;
import com.vframework.base.model.LogBean;
import com.vframework.base.service.BaseService;
import com.vframework.common.constant.GlobalConstant;
import com.vframework.common.constant.SessionConstant;
import com.vframework.system.menu.model.MenuBean;
/***************************************************************
 * Name:        BaseController.java
 * Create At:   2018年4月12日
 * Module:      
 * Description: [各模块Controller必须继承此类，用于全局的封装]
 * @author      shanzhitong
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2018年4月12日      shanzhitong    
 * 2
***************************************************************/
public abstract class BaseController{
    
    /**
     * 管理基础路径
     */
//    @Value("${spring.mvc.view.prefix}")
    protected String adminPath = "admin";
    
    /**
     * 前端URL后缀
     */
//    @Value("${urlSuffix}")
    protected String urlSuffix = ".do";
    
	@Autowired
	@Qualifier("baseServiceImpl")
	private BaseService baseService;
	//分页记录数
	protected int pageSize = 10;
	//各页面共通request
	protected HttpServletRequest request;
	//保存查询条件参数
	protected Map<String, Object> paramMap;
	//各页面共通session
	protected Session session;
	//各页面共通model
	protected Model model;

	/**
	 * Author:shanzhitong
     * Create At:2010-04-22
     * Description: [初始化请求]
	 * @throws IllegalAccessException 
     */
	@ModelAttribute
    protected void handle(HttpServletRequest request, Model model) throws Exception {
    	this.request = request;
    	this.model = model;
    	this.model.addAttribute("message", null);
		session = SecurityUtils.getSubject().getSession();
		String operatorOrgId = (String)session.getAttribute(SessionConstant.SESSION_ORG_ID);
		String operatorId = (String)session.getAttribute(SessionConstant.SESSION_USER_ID);
		String operator = (String)session.getAttribute(SessionConstant.SESSION_USER_NAME);
		paramMap = new BaseMap();
		paramMap = ResetParamMap(request);
		paramMap.put("cur_orgId", operatorOrgId);
		paramMap.put("cur_userId", operatorId);
		paramMap.put("cur_userName", operator);
		setSessionMenu(request.getParameter("cur_menu_id"));
    };
	
    protected void message(String msg) {
        this.model.addAttribute("message", msg);
    }
    
	/**
	* Author:shanzhitong
	* Create At:2011-9-10
	* Description: [设置分页参数 将起始条数param_curpage 和结束条数param_ipagecount 放入paramMap]
	* @return void
	*/
	protected void setPageInfo(int pageCount){
		String _curpage = null;
		String _ipagecount = null;
		if(paramMap.get("param_curpage")!=null){
			_curpage = String.valueOf(paramMap.get("param_curpage"));
		}
		if(paramMap.get("param_ipagecount")!=null){
			_ipagecount = String.valueOf(paramMap.get("param_ipagecount"));
		}
		//一共多少页
		int j = (_curpage != null && !"".equals(_curpage)) ?Integer.parseInt(_curpage) : 1;
		//每页显示多少条
		int p = (_ipagecount != null && !"".equals(_ipagecount) ) ? Integer.parseInt(_ipagecount) : 20;
		//改变查询条件不点击查询按钮，直接点翻页，如果输入的查询条件查询不出这么多数据，那么设置为第一页
		int totalPage;
		if (pageCount % p == 0) {
			totalPage = pageCount / p;
	    }
        else {
        	totalPage = pageCount / p + 1;
        }
		if(j > totalPage){
			j = 1;
		}
		//每页的起始条数		
		paramMap.put("param_curpage",p*(j-1));
		//每页显示多少条
		paramMap.put("param_ipagecount",p);
		//一共多少页
		request.setAttribute("param_curpage",j);
		//每页显示多少条
		request.setAttribute("param_ipagecount",p);
		//共多少页
		request.setAttribute("param_totalPage",totalPage);
		//共多少条
		request.setAttribute("param_totalCount",pageCount);
	}
	
	protected String LOG_LOGIN_KEY = "0";//登录
	protected String LOG_ADD_KEY = "1";//增加
	protected String LOG_UPDATE_KEY = "2";//修改
	protected String LOG_DELETE_KEY = "3";//删除
	protected String LOG_COUNT_KEY = "4";//统计
	protected String LOG_IMPORT_KEY = "5";//导入
	protected String LOG_EXPORT_KEY = "6";//导出
	
    /**
     * Description: 绑定日志Bean
     * @param optype 操作类型 1增加、2修改、3删除、4统计、5导入、6导出、0登录
     * @param content 参数toString()
     * @param remark 操作描述
     */
    protected LogBean MakeLogBean(String optype, String remark, String content) {
        session = SecurityUtils.getSubject().getSession();
    	LogBean logBean= new LogBean();
    	logBean.setOrgId((String)session.getAttribute(SessionConstant.SESSION_ORG_ID));
    	logBean.setMenuId((String)session.getAttribute(SessionConstant.SESSION_CUR_MENU_ID));
    	logBean.setMenuName((String)session.getAttribute(SessionConstant.SESSION_CUR_TRAGET_PATH));
    	logBean.setOperateType(optype);
    	logBean.setRemark(remark);
    	logBean.setContent(content);
    	logBean.setIp(getIpAddr());
    	logBean.setOperator((String)session.getAttribute(SessionConstant.SESSION_USER_NAME));
    	logBean.setOperatorId((String)session.getAttribute(SessionConstant.SESSION_USER_ID));
//    	logBean.setRole((String)session.getAttribute(SessionConstant.SESSION_USER_ROLE));
		return logBean;
	}

	/**
	* Author:shanzhitong
	* Create At:2011-9-2
	* Description: [持久保存用户关键信息到session，并适时更新]
	* @return void
	*/
	private void setSessionMenu(String menuId) {
		if(menuId!=null && request!=null){
			request.getSession().setAttribute(SessionConstant.SESSION_CUR_MENU_ID, menuId);
			String userId = (String) request.getSession().getAttribute(SessionConstant.SESSION_USER_ID);
			if(menuId.length()>0 && userId!=null && userId.length()>0){
				if(baseService != null){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("menuId", menuId);
					map.put("userId", userId);
					MenuBean menu = null;
                    try {
                        menu = baseService.getSessionMenu(map);
                    } catch (BaseException e) {
                        e.printStackTrace();
                    }
					request.getSession().setAttribute(SessionConstant.SESSION_CUR_MENU, menu);
					request.getSession().setAttribute(SessionConstant.SESSION_CUR_MENU_PATH,menu.getMenuPath());
					request.getSession().setAttribute(SessionConstant.SESSION_CUR_TRAGET_PATH,menu.getTargetPath());
					//sessionMap.put(SessionConstant.SESSION_CUR_MENU, menu);
				}
			}
		}
	}
	
    /**
	 * Author:shanzhitong
     * Create At:2010-04-22
     * Description:保存查询条件,封装查询条件参数
     * @param request
     * @return Map<String, Object> paramMap
     */
	private Map<String, Object> ResetParamMap(HttpServletRequest request){
        //查询所有form中元素.
        Enumeration<String> params = request.getParameterNames();
        String value = null;
        while (params.hasMoreElements()) {
        	//得到下一个元素
            String paramName = params.nextElement();
            //比较paramName的开始
            if (paramName.startsWith(GlobalConstant.PARAMETER_SIGN)) {
            	value = request.getParameter(paramName).trim();
            	request.setAttribute(paramName, value);
            	//对搜索关键字进行转义
            	if(paramName.equals("param_keyWord")){
            	    value = StringUtil.decode(value);
            		value = value.replace("%", "\\%");
            		value = value.replace("_", "\\_");
            	}
            	paramMap.put(paramName, value);
            }
        }
		return paramMap;
    }

	/**
     * 初始化数据绑定
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
//                setValue(DateUtil.toDate(text));
            }
//          @Override
//          public String getAsText() {
//              Object value = getValue();
//              return value != null ? DateUtils.formatDateTime((Date)value) : "";
//          }
        });
    }
    
    /**
     *获得客户端真实IP地址的方法
     * @return
     */
    protected String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
